﻿using Nancy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Nancy.Bootstrapper;
using Nancy.Conventions;
using Nancy.Session;
using Nancy.TinyIoc;
using System.Configuration;

namespace customer.dao
{
    public class CustomBootstrapper: DefaultNancyBootstrapper
    {

        public string AccessToken
        {
            get
            {   
                var k = ConfigurationManager.AppSettings["AccessToken"];
                return k;
            }
        }

        protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
        {
            pipelines.BeforeRequest.AddItemToStartOfPipeline(ctx =>
            {
                if (ctx.Request.Url.Path.ToLower().Contains("odata") == false)
                {   
                    return null;
                }

                var at = ctx.Request.Headers["AT"].FirstOrDefault();
                if (!string.IsNullOrWhiteSpace(at) && at.Equals(this.AccessToken))
                {   
                    return null;
                }
                else
                {   
                    Response rps = new Response();
                    rps.StatusCode = HttpStatusCode.Forbidden;

                    return rps;
                }
            });

            pipelines.AfterRequest.AddItemToEndOfPipeline(ctx =>
            {
                ctx.Response.Headers.Add("Access-Control-Allow-Origin", "*");
                ctx.Response.Headers.Add("Access-Control-Allow-Methods", "POST,GET,DELETE,PUT,OPTIONS");
                //ctx.Response.Headers.Add("Access-Control-Allow-Credentials", "true");

                ctx.Response.Headers.Add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");

            });

            CookieBasedSessions.Enable(pipelines);
        }
    }
}
